require 'json'
require 'singleton'

module LiJia
module SolidName

  # 本文件是要变更的名称的Hash容器
  # 结构为：[solid_1_pid:[source_name_1, destination_name_1], solid_2_pid:[source_name_2, destination_name_2], ...]
  # 实现Singleton单例模式，确保此容器唯一

  class NameContainer include Singleton

    # 初始化构造函数
    def init_container(change_mode)

      change_mode = LiJia::SolidName::CHANGE_MODE[:Layer_Instance] if change_mode == nil
      @name_container_hash = Hash.new if @name_container_hash == nil

      # 获得所有可见的实体（组件/群组）
      ents = Sketchup.active_model.entities.select{|entity| entity.visible? && LiJia::SolidName.is_solid?(entity)}

      ents.each{|level_1_solid| 
        level_2_solids = level_1_solid.definition.entities.select{|sub_ent| 
          sub_ent.visible? && LiJia::SolidName.is_solid?(sub_ent)
        }
        level_2_solids.each{|level_2_solid|
          @name_container_hash[level_2_solid.persistent_id] = NamePair.new(level_2_solid, change_mode)
        }
      }
    end

    # 根据pid，取指定实体的NamePair
    def get_namepair(pid)
      return @name_container_hash[pid]
    end

    def to_json()
      json_ready_hash = @name_container_hash.transform_values(&:to_json)
      return json_ready_hash.to_json
    end

  end # class NameContainer


  # 名称对。包括每个实体的源名称、目的名称
  class NamePair

    attr_accessor :source_name, :destination_name

    # 初始化方法
    def initialize(solid, change_mode)
      if(change_mode == LiJia::SolidName::CHANGE_MODE[:Layer_Instance])
        @source_name = solid.layer.name
        @destination_name = solid.name
      elsif(change_mode == LiJia::SolidName::CHANGE_MODE[:Layer_Definition])
        @source_name = solid.layer.name
        if solid.is_a? Sketchup::ComponentInstance
          @destination_name = solid.definition.name
        else
          @destination_name = solid.name
        end
      end
    end

  def to_json(*a)
  {
    sourceName: @source_name,
    destName: @destination_name
  }.to_json

  end

  end # class NamePair

end # module SolidName
end # module LiJia  